<html>
<head>
    <meta charset="utf-8"/>
<meta name="description" content=""/>
<meta name="viewport" content="width=device-width, initial-scale=1"/>

<title>稀疏数组实现棋盘存储与恢复 | 絷缘的博客</title>

<link rel="shortcut icon" href="https://zydnc.gitee.io/favicon.ico?v=1732378515642">

<link href="https://cdn.jsdelivr.net/npm/@fortawesome/fontawesome-free/css/all.min.css" rel="stylesheet">
<link rel="stylesheet" href="https://zydnc.gitee.io/styles/main.css">
<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap@4.5.0/dist/css/bootstrap.min.css">

<script src="https://cdn.jsdelivr.net/npm/@highlightjs/cdn-assets/highlight.min.js"></script>
<script src="https://cdn.bootcss.com/highlight.js/9.15.10/languages/dockerfile.min.js"></script>
<script src="https://cdn.bootcss.com/highlight.js/9.15.10/languages/dart.min.js"></script>

<script src="https://cdn.jsdelivr.net/npm/moment@2.27.0/moment.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/jquery@3.5.1/dist/jquery.slim.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/popper.js@1.16.0/dist/umd/popper.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/bootstrap@4.5.0/dist/js/bootstrap.min.js"></script>
<!-- DEMO JS -->
<!--<script src="media/scripts/index.js"></script>-->



    <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/katex@0.12.0/dist/katex.css">
 <script src='//unpkg.com/valine/dist/Valine.min.js'></script>
</head>
<body>
<div class="main gt-bg-theme-color-first">
    <nav class="navbar navbar-expand-lg">
    <div class="navbar-brand">
        <img class="user-avatar" src="/images/avatar.png" alt="头像">
        <div class="site-name gt-c-content-color-first">
            絷缘的博客
        </div>
    </div>
    <button class="navbar-toggler" type="button" data-toggle="collapse" data-target="#navbarSupportedContent"
            aria-controls="navbarSupportedContent" aria-expanded="false" aria-label="Toggle navigation">
        <i class="fas fa-bars gt-c-content-color-first" style="font-size: 18px"></i>
    </button>
    <div class="collapse navbar-collapse" id="navbarSupportedContent">
        <div class="navbar-nav mr-auto" style="text-align: center">
            
                <div class="nav-item">
                    
                        <a href="/" class="menu gt-a-link">
                            首页
                        </a>
                    
                </div>
            
                <div class="nav-item">
                    
                        <a href="/archives" class="menu gt-a-link">
                            归档
                        </a>
                    
                </div>
            
                <div class="nav-item">
                    
                        <a href="/tags" class="menu gt-a-link">
                            标签
                        </a>
                    
                </div>
            
                <div class="nav-item">
                    
                        <a href="/about" class="menu gt-a-link">
                            关于
                        </a>
                    
                </div>
            
                <div class="nav-item">
                    
                        <a href="/friends" class="menu gt-a-link">
                            友链
                        </a>
                    
                </div>
            
        </div>
        <div style="text-align: center">
            <form id="gridea-search-form" style="position: relative" data-update="1732378515642" action="/search/index.html">
                <input class="search-input" autocomplete="off" spellcheck="false" name="q" placeholder="搜索文章" />
                <i class="fas fa-search gt-c-content-color-first" style="position: absolute; top: 9px; left: 10px;"></i>
            </form>
        </div>
    </div>
</nav>

    <div class="post-container">
        <div class="post-detail gt-bg-theme-color-second">
            <article class="gt-post-content">
                <h2 class="post-title">
                    稀疏数组实现棋盘存储与恢复
                </h2>
                <div class="post-info">
                    <time class="post-time gt-c-content-color-first">
                        · 2021-02-01 ·
                    </time>
                    
                        <a href="https://zydnc.gitee.io/datastructure/" class="post-tags">
                            # 数据结构
                        </a>
                    
                        <a href="https://zydnc.gitee.io/4Qa1Vqi9a/" class="post-tags">
                            # 稀疏数组
                        </a>
                    
                        <a href="https://zydnc.gitee.io/java/" class="post-tags">
                            # Java
                        </a>
                    
                </div>
                <div class="post-content">
                    <h2 id="一-导入jackson依赖">一、导入Jackson依赖</h2>
<blockquote>
<p>为了将对象序列化为XML文件，将XML反序列化为对象</p>
</blockquote>
<pre><code class="language-xml">&lt;dependency&gt;
    &lt;groupId&gt;com.fasterxml.jackson.dataformat&lt;/groupId&gt;
    &lt;artifactId&gt;jackson-dataformat-xml&lt;/artifactId&gt;
    &lt;version&gt;2.9.8&lt;/version&gt;
&lt;/dependency&gt;
</code></pre>
<h2 id="二-创建棋盘数据信息bean对象">二、创建棋盘数据信息Bean对象</h2>
<blockquote>
<p>将稀疏数组存储为对象</p>
</blockquote>
<pre><code class="language-java">public class SparseArray {
    private int row;
    private int col;
    private int count;
    private Array [] data;

    public SparseArray() {}

    public SparseArray(int row, int col, int count, Array[] data) {
        this.row = row;
        this.col = col;
        this.count = count;
        this.data = data;
    }

    public void setRow(int row) {
        this.row = row;
    }

    public void setCol(int col) {
        this.col = col;
    }

    public void setCount(int count) {
        this.count = count;
    }

    public void setData(Array[] data) {
        this.data = data;
    }

    public int getRow() {
        return row;
    }

    public int getCol() {
        return col;
    }

    public int getCount() {
        return count;
    }

    public Array[] getData() {
        return data;
    }
}
</code></pre>
<pre><code class="language-java">public class Array {
    private int row;
    private int col;
    private int value;

    public Array() {}

    public Array(int row, int col, int value) {
        this.row = row;
        this.col = col;
        this.value = value;
    }

    public void setRow(int row) {
        this.row = row;
    }

    public void setCol(int col) {
        this.col = col;
    }

    public void setValue(int value) {
        this.value = value;
    }

    public int getRow() {
        return row;
    }

    public int getCol() {
        return col;
    }

    public int getValue() {
        return value;
    }
}
</code></pre>
<h2 id="三-实现棋盘存储与恢复">三、实现棋盘存储与恢复</h2>
<blockquote>
<p>将数据对象序列化到XML配置文件中，实现存储棋盘<br>
将XML配置反序列化为数据对象，实现恢复棋盘</p>
</blockquote>
<pre><code class="language-java">public class SparsearrayDemo1 {
    public static void main(String[] args) {
        // 创建一个原始的二维数组
        // 0：表示没有棋子，1：表示黑子，2：表示白子
        int [][]chessArray = new int [11][11];
        chessArray[1][2] = 1;
        chessArray[2][3] = 2;
        chessArray[4][5] = 2;
        System.out.println(&quot;原数组内容：&quot;);
        for (int[] ints : chessArray) {
            System.out.println(Arrays.toString(ints));
        }
        // 遍历二维数组获得非零元素个数
        int count = 0;
        for (int[] value : chessArray) {
            for (int j = 0; j &lt; value.length; j++) {
                if (value[j] != 0) {
                    count++;
                }
            }
        }
        System.out.println(&quot;非零个数：&quot; + count);
        int [][] sparseArray = new int [count+1][3];
        int row = chessArray.length;
        int col = chessArray[0].length;
        sparseArray[0][0] = row;
        sparseArray[0][1] = col;
        sparseArray[0][2] = count;
        int num = 0;
        for (int i = 0; i &lt; chessArray.length; i++) {
            for (int j = 0; j &lt; chessArray[i].length; j++) {
                if (chessArray[i][j]!=0){
                    sparseArray[++num][0] = i;
                    sparseArray[num][1] = j;
                    sparseArray[num][2] = chessArray[i][j];
                }
            }
        }
        //创建存储棋盘数据的对象
        SparseArray info = new SparseArray();
        info.setRow(sparseArray[0][0]);
        info.setCol(sparseArray[0][1]);
        info.setCount(sparseArray.length-1);
        Array [] arrays = new Array[sparseArray.length-1];
        for (int i = 1; i &lt; sparseArray.length; i++) {
            Array array = new Array();
            array.setRow(sparseArray[i][0]);
            array.setCol(sparseArray[i][1]);
            array.setValue(sparseArray[i][2]);
            arrays[i-1] = array;
        }
        info.setData(arrays);
        System.out.println(&quot;开始存储棋盘1&quot;);
        File file = new File(&quot;./sparsearray.xml&quot;);
        saveBoard(file,info);
        System.out.println(&quot;棋盘存储成功&quot;);
        System.out.println(&quot;开始恢复棋盘&quot;);
        int[][] ints = recoverBoard(file, SparseArray.class);
        for (int[] anInt : ints) {
            System.out.println(Arrays.toString(anInt));
        }
        System.out.println(&quot;棋盘恢复成功&quot;);
    }
    public static void saveBoard(File file,SparseArray info){
        //将对象序列化为xml文件存储
        try {
            if(!file.exists()){
                file.createNewFile();
            }
            fromObjectToXML(file,info);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
    public static int [][] recoverBoard(File file,Class cls){
        if(file.exists()){
            SparseArray info = (SparseArray)fromXMLToObject(file, cls);
            int [][] newArray = new int [info.getRow()][info.getCol()];
            Array[] data = info.getData();
            for (int i = 0; i &lt; data.length; i++) {
                newArray[data[i].getRow()][data[i].getCol()] = data[i].getValue();
            }
            return newArray;
        }
        return null;
    }
    public static void fromObjectToXML(File file,Object data){
        BufferedWriter bw = null;
        XmlMapper xmlMapper = new XmlMapper();
        try {
            String xml = xmlMapper.writerWithDefaultPrettyPrinter().writeValueAsString(data);
            bw = new BufferedWriter(new FileWriter(file));
            bw.write(xml,0,xml.length());
        } catch (JsonProcessingException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }finally {
            try {
                bw.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
    public static Object fromXMLToObject(File file,Class cls){
        BufferedReader br = null;
        XmlMapper xmlMapper = new XmlMapper();
        Object sparseArray = null;
        try {
            sparseArray = xmlMapper.readValue(new FileInputStream(file), cls);
        } catch (IOException e) {
            e.printStackTrace();
        }
        return sparseArray;
    }
}
</code></pre>
<h2 id="四-查看存储的棋局">四、查看存储的棋局</h2>
<pre><code class="language-xml">&lt;SparseArray&gt;
  &lt;row&gt;11&lt;/row&gt;
  &lt;col&gt;11&lt;/col&gt;
  &lt;count&gt;3&lt;/count&gt;
  &lt;data&gt;
    &lt;data&gt;
      &lt;row&gt;1&lt;/row&gt;
      &lt;col&gt;2&lt;/col&gt;
      &lt;value&gt;1&lt;/value&gt;
    &lt;/data&gt;
    &lt;data&gt;
      &lt;row&gt;2&lt;/row&gt;
      &lt;col&gt;3&lt;/col&gt;
      &lt;value&gt;2&lt;/value&gt;
    &lt;/data&gt;
    &lt;data&gt;
      &lt;row&gt;4&lt;/row&gt;
      &lt;col&gt;5&lt;/col&gt;
      &lt;value&gt;2&lt;/value&gt;
    &lt;/data&gt;
  &lt;/data&gt;
&lt;/SparseArray&gt;
</code></pre>
<h2 id="五-控制台打印结果">五、控制台打印结果</h2>
<pre><code class="language-java">原数组内容：
[0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]
[0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0]
[0, 0, 0, 2, 0, 0, 0, 0, 0, 0, 0]
[0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]
[0, 0, 0, 0, 0, 2, 0, 0, 0, 0, 0]
[0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]
[0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]
[0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]
[0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]
[0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]
[0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]
非零个数：3
开始存储棋盘
棋盘存储成功
开始恢复棋盘
[0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]
[0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0]
[0, 0, 0, 2, 0, 0, 0, 0, 0, 0, 0]
[0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]
[0, 0, 0, 0, 0, 2, 0, 0, 0, 0, 0]
[0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]
[0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]
[0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]
[0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]
[0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]
[0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]
棋盘恢复成功
</code></pre>
<blockquote>
<p>原文作者：絷缘<br>
作者邮箱：zhiyuanworkemail@163.com<br>
原文地址：<a href="https://zhiyuandnc.github.io/ZZGM9B12P/">https://zhiyuandnc.github.io/ZZGM9B12P/</a><br>
版权声明：本文为博主原创文章，转载请注明原文链接作者信息</p>
</blockquote>

                </div>
            </article>
        </div>

        
            <div class="next-post">
                <div class="next gt-c-content-color-first">下一篇</div>
                <a href="https://zydnc.gitee.io/WvJdcATYk/" class="post-title gt-a-link">
                    Redis数据库简单学习
                </a>
            </div>
        

        

        

        

        <div class="site-footer gt-c-content-color-first">
    <div class="slogan gt-c-content-color-first">事实不以人的意志为转移</div>
    <div class="social-container">
        
            
                <a href="#" target="_blank">
                    <i class="fab fa-github gt-c-content-color-first"></i>
                </a>
            
        
            
                <a href="#" target="_blank">
                    <i class="fab fa-telegram gt-c-content-color-first"></i>
                </a>
            
        
            
                <a href="#" target="_blank">
                    <i class="fab fa-qq gt-c-content-color-first"></i>
                </a>
            
        
            
                <a href="#" target="_blank">
                    <i class="fab fa-bilibili gt-c-content-color-first"></i>
                </a>
            
        
            
        
            
        
            
        
            
        
            
        
            
        
            
        
            
        
            
        
    </div>
    <div class="footer-info">
        Copyright&ensp;&copy;&ensp;絷缘的博客<br/><a href="https://beian.miit.gov.cn/" target="_blank">晋ICP备20001723号-1</a>
    </div>
    <div>
        Theme by <a href="https://imhanjie.com/" target="_blank">imhanjie</a>, Powered by <a
                href="https://github.com/getgridea/gridea" target="_blank">Gridea | <a href="https://zydnc.gitee.io/atom.xml" target="_blank">RSS</a></a>
    </div>
</div>

<script>
  hljs.initHighlightingOnLoad()
</script>

    </div>
</div>
</body>
</html>
